import request from '@/utils/http'

// 用户响应（与后端 UserResponse 对齐）
export interface UserResponse {
  id?: number
  username: string
  name?: string | null
  avatar?: string | null
  email?: string | null
  phone?: string | null
  status?: number | null
  department?: string | null
  dept_name?: string | null
  person_id?: number | null
  roles?: number[]
  create_time?: string | null
  update_time?: string | null
}

// 列表响应
export interface UserListResponse {
  total: number
  items: UserResponse[]
  page: number
  size: number
  pages: number
}

// 创建/更新请求体（与后端 UserCreate / UserUpdate 对齐）
export interface UserCreate {
  username: string
  password: string
  name?: string | null
  avatar?: string | null
  email?: string | null
  phone?: string | null
  status?: number
  department?: string | null
  person_id?: number | null
  roles?: number[]
}

export interface UserUpdate {
  username?: string
  name?: string | null
  avatar?: string | null
  email?: string | null
  phone?: string | null
  status?: number
  department?: string | null
  person_id?: number | null
  roles?: number[]
}

// 查询参数（与后端 UserQuery 对齐），注意 current 是 page 的别名
export interface UserQuery {
  current?: number
  size?: number
  username?: string
  name?: string
  email?: string
  phone?: string
  department?: string
  status?: number
  create_time?: string
  update_time?: string
  keyword?: string
}

export interface PasswordChangeRequest {
  old_password: string
  new_password: string
}

/**
 * 创建用户
 */
export function createUser(params: UserCreate) {
  return request.post<UserResponse>({
    url: '/system/users/create',
    params,
    showSuccessMessage: true
  })
}

/**
 * 获取用户列表（分页）
 */
export function fetchUserList(params: UserQuery) {
  return request.post<UserListResponse>({
    url: '/system/users/list',
    params
  })
}

/**
 * 更新用户
 */
export function updateUser(userId: number, params: UserUpdate) {
  return request.put<UserResponse>({
    url: `/system/users/${userId}`,
    params,
    showSuccessMessage: true
  })
}

/**
 * 删除用户
 */
export function deleteUser(userId: number) {
  return request.del<{ message: string }>({
    url: `/system/users/${userId}`,
    showSuccessMessage: true
  })
}

/**
 * 修改用户密码
 */
export function changeUserPassword(userId: number, params: PasswordChangeRequest) {
  return request.post<{ message: string }>({
    url: `/system/users/${userId}/password`,
    params,
    showSuccessMessage: true
  })
}

/**
 * 获取当前用户信息（/me）
 */
export function fetchMe() {
  return request.get<UserResponse>({
    url: '/system/users/me'
  })
}